package com.example.redis6.controller;

import com.example.redis6.model.VideoDo;
import com.example.redis6.util.JsonData;
import com.example.redis6.vo.UserPointVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * description: VideoController <br>
 * date: 2021/7/20 16:07 <br>
 *
 * @author: ZhangYixin <br>
 * version: 1.0 <br>
 */
@RestController
@RequestMapping("/api/v1/videoRank")
public class VideoRankController {

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String DAILY_RANK_KEY = "video:rank:daily";

    @RequestMapping("rank")
    public JsonData videoRank(){
        List<VideoDo> list = redisTemplate.opsForList().range(DAILY_RANK_KEY, 0, -1);
        return JsonData.buildSuccess(list);
    }

    /**
     * 返回所有信息，从大到小
     * @return
     */
    @RequestMapping("realRank1")
    public JsonData realRank1(){
        BoundZSetOperations<String, UserPointVo> operations = redisTemplate.boundZSetOps("point:rank:real");

        Set<UserPointVo> userPointVos = operations.reverseRange(0, -1);
        return JsonData.buildSuccess(userPointVos);
    }

    /**
     * 返回所有信息，从小到大
     * @return
     */
    @RequestMapping("realRank2")
    public JsonData realRank2(){
        BoundZSetOperations<String, UserPointVo> operations = redisTemplate.boundZSetOps("point:rank:real");

        Set<UserPointVo> userPointVos = operations.range(0, -1);
        return JsonData.buildSuccess(userPointVos);
    }

    /**
     * 返回所有信息，从大到小 指定长度
     * @return
     */
    @RequestMapping("realRank3")
    public JsonData realRank3(){
        BoundZSetOperations<String, UserPointVo> operations = redisTemplate.boundZSetOps("point:rank:real");

        Set<UserPointVo> userPointVos = operations.reverseRange(0, 3);
        return JsonData.buildSuccess(userPointVos);
    }

    /**
     * 排名查询
     * @return
     */
    @RequestMapping("findMyRank")
    public JsonData findMyRank(String phone,String name){
        BoundZSetOperations<String, UserPointVo> operations = redisTemplate.boundZSetOps("point:rank:real");

        UserPointVo userPointVo = new UserPointVo(name, phone);
        Long rank = operations.reverseRank(userPointVo);

        return JsonData.buildSuccess(++rank);
    }

    /**
     * 加积分
     * @return
     */
    @RequestMapping("upRank")
    public JsonData upRank(String phone,String name,int point){
        BoundZSetOperations<String, UserPointVo> operations = redisTemplate.boundZSetOps("point:rank:real");

        UserPointVo userPointVo = new UserPointVo(name, phone);

        Double aDouble = operations.incrementScore(userPointVo, point);

        return JsonData.buildSuccess(aDouble);
    }


}
